// 传送数据， 相当于  channel 的消息传送
// tokio async task send message to worker for expansive blocking task

use anyhow::{ Result};
use std::{  thread, time::Duration};
use tokio::{sync::mpsc};



#[tokio::main]
async fn main() ->Result<()> {

    let (tx,rx) = mpsc::channel(32);  // 32 是任务的数量, 超过这个数量， 就要放到 waiter_queue     let handler = worker(rx);

    let handler = worker(rx);
    

    tokio::spawn(async move {
        //let mut rng = rand::rng();
        let mut i = 0;
        loop {
            i +=1;
            println!("send task {i}!");
          // let num  =  3;
            tx.send( format!("Future {i}").to_string()).await?
        }

      #[allow(unreachable_code)]
       Ok::<(),anyhow::Error<>> (())
    });


    handler.join().unwrap();

    Ok(())

}



fn worker(mut rx: mpsc::Receiver<String>) -> thread::JoinHandle<()> {
    thread::spawn(move || {
        while let Some(s) = rx.blocking_recv() {   // 这个在同步的里面， 用blocking_recv， 如果是在异步的里， 则用 recv
            let ret = expensive_blocking_task(s);
            println!("result is {}", ret);

        }
    })
}

// fn tokio_worker(rx:mpsc::Receiver<String>) -> tokio::task::JoinHandle<()> {
//     tokio::spawn(async {
//         rx.recv();
//     })
// }


fn expensive_blocking_task(s: String) -> String{
    thread::sleep(Duration::from_secs(1));
    blake3::hash(s.as_bytes()).to_string()
    
}